"use strict";

process.chdir(__dirname);

const titbit = require("titbit"); //会去上级目录寻找
const fs = require("fs");
const dbcfg = require("./dbconfig.js");
const pg = require("pg");
const wxkey = require("./wxkey.js");
const { httpcli } = require("gohttp");
const token = require("titbit-token");
const tbloader = require("titbit-loader");

try {
    fs.accessSync("./images");
} catch (e) {
    fs.mkdirSync("./images");
}

let psql = new pg.Pool(dbcfg);

let cert_path = "/usr/local/share";

const app = new titbit({
    // 开启测试模式,若有错误会输出错误信息
    debug: true,
    // 开启全局日志
    globalLog: true,
    cert: `${cert_path}/api.hiehie.top.pem`,
    key: `${cert_path}/api.hiehie.top.key`,
});

let tb = new tbloader();
tb.init(app);

// c.service指向app.service
app.addService("psql", psql);
app.addService("imagePath", `${__dirname}/images`);

let tok = new token({
    // 解密时的一个超时验证，45秒超时，token有效期，单位为秒
    expires: 60,
    // 必须是32位字符
    key: "qwertyuiopasdfghjklzxcvbnm<>?123",
    // 必须是16位字符
    iv: "1qaz2wsx3edc4rfv",
});

app.addService("tok", tok);

app.get("/mp-login/:code", async (c) => {
    let auth_url =
        `https://api.weixin.qq.com/sns/jscode2session` +
        `?appid=${wxkey.appid}` +
        `&secret=${wxkey.secret}` +
        `&js_code=${c.param.code}` +
        `&grant_type=authorization_code`;
    let ret = await httpcli.get(auth_url).then((res) => {
        return res.json();
    });
    c.send(tok.make(ret));
});

app.run(2346);
